<?php

namespace App\Common\Libs\Ali;

use GuzzleHttp\Client;
use Illuminate\Support\Facades\Storage;

/**
 * 远程图片处理类
 *
 * @time 2020.09.12
 * @author dumpling
 * @package common\libs
 */
class RemoteFile
{
    private static $_remoteFile;

    // 使用get_headers()得到的信息
    private $_headers = [];

    // 远程图片地址
    private $remoteUrl;

    // 保存到本地的文件名
    private $filename;

    // 保存到本地的路径
    private $savePath;

    /**
     * 入口
     * @param $remoteUrl
     * @param $filename
     * @return RemoteFile
     */
    public static function getInstance(string $remoteUrl, string $filename = null): self
    {
        if (self::$_remoteFile === null) {
            self::$_remoteFile = new self();
        }

        $client = new Client(['verify' => false]);
        $response = $client->get($remoteUrl);
        $header = $response->getHeaders();
        $content = $response->getBody()->getContents();

        self::$_remoteFile->remoteUrl = $remoteUrl;
        self::$_remoteFile->savePath = storage_path('downloads/');
        self::$_remoteFile->_headers = $header;

        self::$_remoteFile->filename = self::$_remoteFile->getFilename($remoteUrl, $filename);

        Storage::disk('oss')->put('downloads/' . self::$_remoteFile->filename, $content);

        return self::$_remoteFile;
    }

    /**
     * @return array
     */
    public function downloadToLocal()
    {
        return [
            'path' => $this->savePath,
            'filename' => $this->filename,
            'size' => $this->getSize(),
            'postfix' => $this->getExtension(),
            'file_mime' => $this->getMime(),
        ];
    }

    /**
     * 设置保存的路径，默认时common/download/
     * @param $savePath
     * @return bool
     */
    public function setSavePath($savePath): bool
    {
        $this->savePath = $savePath;

        return true;
    }

    /**
     * 根据远程图片mime，截取具体类型
     *
     * @return string
     */
    public function getExtension(): string
    {
        $mime = $this->getMime();

        if (strpos($mime, 'svg') !== false) {
            return 'svg';
        }

        $extension = substr($mime, strrpos($mime, '/') + 1);
        if ($extension == 'jpeg') {
            return 'jpg';
        }

        return $extension;
    }

    public function getFilename($url, $filename = '')
    {
        if ($filename) {
            return $filename;
        }

        $extension = self::$_remoteFile->getExtension();

        return self::getBaseFilename($url) . '.' . $extension;
    }

    public static function getBaseFilename($url)
    {
        return md5($url);
    }

    public static function getRemoteUrlSign($url)
    {
        return self::getBaseFilename($url);
    }

    /**
     * 从header中获取远程图片mime，也就是Content-Type
     *  注意：
     *    1. 当远程图片时svg时，mime = Content-Type = 'image/svg+xml'
     * @return string
     */
    private function getMime(): string
    {
        return $this->_headers['Content-Type'][0] ?? 'image/jpg';
    }

    /**
     * 从header中获取图片大小，也就是Content-Length
     *
     * @return string
     */
    private function getSize(): string
    {
        if (is_array($this->_headers['Content-Length'])) {
            return $this->_headers['Content-Length'][0];
        }
        return $this->_headers['Content-Length'];
    }
}
